#!/bin/sh

## hyphop ##

#= mini downloader

#GET(){

	[ "$MAXTRY" ] || \
	    MAXTRY=30
	[ "$DL_MIN_SPEED" ] || \
	    DL_MIN_SPEED=10000
	[ "$DL_MIN_SPEED_TIME" ] || \
	    DL_MIN_SPEED_TIME=3


    [ "$1" ] || { 
	echo "[w] undef src">&2
	return 1
    }

OK(){
	md5sum "$O_" > "$O_.md5sum"
	cd $P_
	exit 0
#	return 0
}

    D_="$2"
    O_="$3"

    [ "$O_" ] || O_="$(basename "$1")"
    [ "$D_" ] || D_="$DOWNLOADS"
    
    echo "[i] DOWNLOAD $1 => $O_ DIR $D_">&2

    T_=/tmp/dl.head
    P_=$(pwd)
    [ $D_ ] && {
	cd $D_ || { echo "[e] change dir to $D_">&2
	exit 1
        }
    }
    [ -f "$O_.md5sum" ] && {
	echo "[w] already downloaded">&2
	cd $P_
	return 0
    }

    case "$1" in
	*//mega*)
	[ "$megadl" ] || \
	megadl=$(which megadl)
	[ "$?" = 0 ] || {
	    echo "[e] megadl not found">&2
	    return 1
	}
	r_=0
	$megadl --print-names "$1" | tee $T_
	o_=$(tail -1 "$T_")
	[ "$o_" = "$O_" ] || \
	CMD mv "$o_" "$O_"
	;;
	*//*)
	r_=
	TRY=0
	while [ "1" ] ; do
	[ "$TRY" -gt "$MAXTRY" ] && {
	    echo "[e] max try $MAXTRY reached">&2
	    exit 1
	}
	[ "$TRY" = "0" ] || \
	echo "[i] try $TRY from $MAXTRY">&2
    

	TRY=$((TRY+1))

	curl -Y $DL_MIN_SPEED -y $DL_MIN_SPEED_TIME \
	     -f -jkL -C- -D "$O_.headers" "$1" -o "$O_"

	r_=$?
	case $r_ in
	    28)
	    echo "[i] restart downloading (slow dl speed)">&2
	    #sleep 1
	    ;;
	    22)
	    echo "[i] curl ret code $r_">&2
	    head -n1 "$O_.headers" | grep 416 && {
	    echo "[i] file already downloaded">&2
	    ##curl: (22) The requested URL returned error: 416
	    OK
	    }
	    ;;
	    0)
	    OK
	    ;;
	    *)
	    echo "[i] curl ret code $r_">&2
	    cat "$O_.headers">&2
	    break
	    ;;
	esac
	done

	#echo "[i] curl ret $r_">&2
	return $r_
	#exit $r_
	;;
    esac

    [ "$r_" = "0" ] && OK

    cd $P_

#}
#
#GET "$LINK" "$IMG" $DL || DIE

